<!--
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-06-15 11:29:46
 * @LastEditTime : 2023-07-24 09:27:23
-->
<!-- eslint-disable @typescript-eslint/no-use-before-define -->
<script lang="ts" setup name="ModelListDesign">
import { _ } from 'iking-utils'
import { downloadFile } from './download-file'
import { useFields } from './fields'

import {
  deleteForm,
  deleteFun,
  deleteList,
  delProject,
  getForm,
  getFun,
  getProject,
  syncFun
} from '@/MainApp/apis/manage-design'

const props = defineProps({
  active: {
    type: String,
    default: 'first'
  }
})

const emits = defineEmits<{
  (event: 'addFun', data: object): void
  (event: 'addForm', data: object): void
  (event: 'edit', data: object): void
  (event: 'preview', data: object): void
  (event: 'handleCreate', data: object): void
  (event: 'handleTabClick', data: object): void
}>()
const { t } = useConfig()
const { msgBoxWarning, msgSuccess, msgError } = useMessage()
// const formDefault: object = inject('formData') || {
//   name: '',
//   scaffoldType: '',
//   createName: ''
// }

const activeName = ref(props.active)

const countTotal = ref(0)
const pageData = ref()
const loading = ref(false)

const projectData = ref<Array<any>>([])

const findChildren = (list: Array<any>) => {
  if (list && list.length > 0) {
    list.forEach(item => {
      item.children = []
      if (item.moduleDTOList) {
        item.children = item.moduleDTOList
        item.children.forEach((ele: any) => {
          ele.children = []
          if (ele.formList)
            ele.children = [...ele.formList]
          if (ele.tabulationList)
            ele.children = [...ele.children, ...ele.tabulationList]
        })
      }
      if (item.formList)
        item.children = item.formList
      if (item.tabulationList)
        item.children = [...item.children, ...item.tabulationList]
    })
    return list
  }
  return []
}
const handFinalAction = (success: boolean) => {
  loading.value = false
  !success && (projectData.value = [])
}
// 查询
const queryProject = async () => {
  loading.value = true
  const param = { ...pageData.value }
  const { success, data, total } = await getProject(param)
  if (success) {
    const projectList = findChildren(data)
    projectData.value = success ? _.cloneDeep(projectList) : []
    countTotal.value = total
  }
  handFinalAction(success)
}
const queryFun = async () => {
  loading.value = true
  const param = { ...pageData.value }
  const { success, data, total } = await getFun(param)
  const projectList = findChildren(data)
  if (success) {
    projectData.value = success ? _.cloneDeep(projectList) : []
    countTotal.value = total
  }
  handFinalAction(success)
}
const queryForm = async () => {
  loading.value = true
  const param = { ...pageData.value }
  const { success, data, total } = await getForm(param)
  if (success) {
    projectData.value = success ? data : []
    countTotal.value = total
  }
  handFinalAction(success)
}
const searchProject = () => {
  switch (activeName.value) {
    case 'first':
      queryProject()
      break
    case 'second':
      queryFun()
      break
    case 'third':
      queryForm()
      break
    default:
      break
  }
}

const handleEditRow = (row: any) => {
  emits('edit', row)
}
const handlePreviewCode = (row: any) => {
  emits('preview', row)
}

// 删除
const handleDelete = (row: any) => {
  if (row.scaffoldType === 'PROJECT') {
    let message = ''
    if (row.moduleDTOList && row?.moduleDTOList.length > 0)
      message = `删除后，工程【${row.name}】及其所有的功能和界面将被一并删除，无法恢复。功能中已添加的表，系统不会主动删除。确定删除吗？`

    else
      message = `确定删除工程【${row.name}】吗？`

    msgBoxWarning('确认删除', message, async () => {
      const { success, msg } = await delProject(row.id)
      if (success) {
        msgSuccess(msg)
        searchProject()
      }
      else {
        msgError(msg)
      }
    })
  }
  if (row.scaffoldType === 'MODULE') {
    let message = ''
    if (row.moduleDTOList && row?.formList.length > 0)
      message = `删除后，功能【${row.name}】及其所有的界面将被一并删除，无法恢复。已添加的表，系统不会主动删除。确定删除吗？`

    else
      message = `确定删除功能【${row.name}】吗？`

    msgBoxWarning('确认删除', message, async () => {
      const { success, msg } = await deleteFun(row.id)
      if (success) {
        msgSuccess(msg)
        searchProject()
      }
      else {
        msgError(msg)
      }
    })
  }
  if (row.scaffoldType === 'PAGE' || row.scaffoldType === 'FORM') {
    msgBoxWarning('确认删除', `确定删除界面【${row.name}】吗？`, async () => {
      const { success, msg } = await deleteForm(row.id)
      if (success) {
        msgSuccess(msg)
        searchProject()
      }
      else {
        msgError(msg)
      }
    })
  }
  if (row.scaffoldType === 'LIST') {
    msgBoxWarning('删除', `确定删除列表【${row.name}】吗？`, async () => {
      const { success, msg } = await deleteList(row.id)
      if (success) {
        msgSuccess(msg)
        searchProject()
      }
      else {
        msgError(msg)
      }
    })
  }
}
const handleClick = async (val?: any) => {
  if (val)
    emits('handleTabClick', val)
  await searchProject()
}
const handleDownloadRow = async (row: any) => {
  await downloadFile(row)
}
const handleSyncRow = async (row: any) => {
  const { success, msg } = await syncFun({
    moduleId: row.id
  })
  if (success) {
    searchProject()
    msgSuccess(msg)
  }
}
const addFun = (row: any) => {
  emits('addFun', row)
}
const addForm = (row: any, str: string) => {
  emits('addForm', { ...row, changeFormType: str })
}
const handleCreate = () => {
  emits('handleCreate', { activeName: activeName.value })
}
const setActiveName = (str: any) => {
  activeName.value = str
  searchProject()
}
defineExpose({
  searchProject,
  handleClick,
  activeName,
  setActiveName
})

const fields = ref([])
useFields().then((res: any) => {
  fields.value = res
})
</script>

<template>
  <IkPageFull
    v-model="pageData"
    header-title=""
    :fields="fields"
    :table-data="projectData"
    :total="countTotal"
    :loading="loading"
    :search="searchProject"
    row-key="id"
  >
    <template #headerRight>
      <!-- v-role="'ADD-USER'" -->
      <el-button type="primary" @click="handleCreate">新增</el-button>
    </template>
    <template #operate="{ data }">
      <IkBtnContent :num="2">
        <IkTooltip v-if="data.row.scaffoldType === 'MODULE' || data.row.scaffoldType === 'PROJECT'" :content="t('action.downloadCode')">
          <IkSvgIcon
            name="iksvg_xiayi"
            show-bg
            :start-margin="false"
            @click="handleDownloadRow(data.row)"
          />
        </IkTooltip>
        <IkTooltip v-if="data.row.scaffoldType === 'MODULE' && data.row.sync" :content="t('action.sync')">
          <IkSvgIcon
            name="iksvg_shuaxin2"
            show-bg
            size="small"
            @click="handleSyncRow(data.row)"
          />
        </IkTooltip>
        <IkTooltip v-if="data.row.scaffoldType === 'PROJECT'" :content="t('action.addFun')">
          <IkSvgIcon
            name="iksvg_guanbibeifen"
            show-bg
            @click="addFun(data.row)"
          />
        </IkTooltip>
        <IkTooltip v-if="data.row.scaffoldType === 'MODULE'" :content="t('action.addPage')">
          <IkSvgIcon
            name="iksvg_guanbibeifen"
            show-bg
            @click="addForm(data.row, 'form')"
          />
        </IkTooltip>
        <IkTooltip v-if="data.row.scaffoldType === 'MODULE' || data.row.scaffoldType === 'PROJECT'" :content="t('action.previewCode')">
          <IkSvgIcon
            name="iksvg_yulan"
            show-bg
            size="small"
            @click="handlePreviewCode(data.row)"
          />
        </IkTooltip>
        <IkTooltip :content="t('action.modify')">
          <IkSvgIcon
            name="iksvg_xiugai"
            show-bg
            size="small"
            @click="handleEditRow(data.row)"
          />
        </IkTooltip>
        <IkTooltip :content="t('action.delete')">
          <IkSvgIcon
            name="iksvg_shanchu1"
            show-bg
            size="small"
            @click="handleDelete(data.row)"
          />
        </IkTooltip>
      </IkBtnContent>
    </template>
  </IkPageFull>
</template>

<style scoped lang="scss">
.gl-content-card{
  margin-top: 0;
}

.w-btn{
    background: #fafafa !important;
    border: none !important;
    padding: 10px !important;
}
</style>
